<?php

/*
	[Discuz!] (C)2001-2007 Comsenz Inc.
	This is NOT a freeware, use is subject to license terms
    mark:has readed
	$Id: discuzcode.func.php 16906 2008-11-27 06:04:49Z cnteacher $
*/

if(!defined('IN_DISCUZ')) {
	exit('Access Denied');
}

//include template('discuzcode');

$discuzcodes = array(
	'pcodecount' => -1,//用于codehtml下标
	'codecount' => 0,//用于所有code标签 DISCUZ_CODE_0,DISCUZ_CODE_1
	'codehtml' => '',//暂存替换后的code代码
	'smiliesreplaced' => 0,//是否替换表情目录
	'seoarray' => array(
		0 => '',
		1 => $_SERVER['HTTP_HOST'],
		2 => $bbname,
		3 => $seotitle,
		4 => $seokeywords,
		5 => $seodescription
	)
);

if(!isset($_DCACHE['bbcodes']) || !is_array($_DCACHE['bbcodes']) || !is_array($_DCACHE['smilies']))
{
	@include DISCUZ_ROOT.'./forumdata/cache/cache_bbcodes.php';
}

//获取附件里面的tag
function attachtag($pid, $aid, &$postlist) {
	global $attachrefcheck, $thumbstatus, $extcredits, $creditstrans, $ftp, $exthtml;
	$attach = $postlist[$pid]['attachments'][$aid];
	if($attach['attachimg']) {
	    $isremote=$attach['remote'] && substr($ftp['attachurl'], 0, 3) == 'ftp' && !$ftp['hideurl'];//合法远程地址
	    //下载附件来路检查
		$attachrefcheck = ($attachrefcheck || $attach['remote']) && !$isremote;
	}
	return attachinpost($attach);//来自discuz.html方法
}
//附件在帖子中如何显示
function attachinpost($attach)
{
    global $attachrefcheck, $extcredits, $creditstrans, $ftp, $thumbstatus;
    $code="";
    if(!isset($attach['unpayed'])) //免费下载或附件过一定时间变免费了
    {
        if ($attach['attachimg']) //可以直接展示图片
        {
            $code .= "<span style=\"position: absolute; display: none\" id=\"attach_$attach[aid]\" onmouseover=\"showMenu(this.id, 0, 1)\"><img src=\"{IMGDIR}/attachimg.gif\" border=\"0\"></span>";
            //stttings为图片附件添加缩略图
            if ($thumbstatus && $attach['thumb'])
            {
                if ($attachrefcheck) {
                    $code .= "<a href=\"###zoom\"><img onclick=\"zoom(this, 'attachment.php?aid=$attach[aid]&amp;noupdate=yes&amp;nothumb=yes')\" src=\"attachment.php?aid=$attach[aid]\" border=\"0\" onmouseover=\"attachimginfo(this, 'attach_$attach[aid]', 1)\" onmouseout=\"attachimginfo(this, 'attach_$attach[aid]', 0, event)\" /></a>";
                } else {
                    $code .= "<a href=\"###zoom\"><img onclick=\"zoom(this, '$attach[url]/$attach[attachment]')\" src=\"$attach[url]/$attach[attachment].thumb.jpg\" border=\"0\" onmouseover=\"attachimginfo(this, 'attach_$attach[aid]', 1)\" onmouseout=\"attachimginfo(this, 'attach_$attach[aid]', 0, event)\" /></a>";
                }
            } else {
                if ($attachrefcheck) {
                    $code .= "<img src=\"attachment.php?aid=$attach[aid]&amp;noupdate=yes\" border=\"0\" onload=\"attachimg(this, 'load')\" onmouseover=\"attachimginfo(this, 'attach_$attach[aid]', 1);attachimg(this, 'mouseover')\" onclick=\"zoom(this, 'attachment.php?aid=$attach[aid]')\" onmouseout=\"attachimginfo(this, 'attach_$attach[aid]', 0, event)\" alt=\"\" />";
                } else {
                    $code .= "<img src=\"$attach[url]/$attach[attachment]\" border=\"0\" onload=\"attachimg(this, 'load')\" onmouseover=\"attachimginfo(this, 'attach_$attach[aid]', 1);attachimg(this, 'mouseover')\" onclick=\"zoom(this, '$attach[url]/$attach[attachment]')\" onmouseout=\"attachimginfo(this, 'attach_$attach[aid]', 0, event)\" alt=\"\" />";
                }
            }
            $code .= "<div class=\"t_attach\" id=\"attach_$attach[aid]_menu\" style=\"position: absolute; display: none\">
    $attach[attachicon] <a href=\"attachment.php?aid=$attach[aid]&amp;nothumb=yes\" target=\"_blank\"><strong>$attach[filename]</strong></a> ($attach[attachsize])<br />";
            if ($attach['description'])
                $code .= "$attach[description]<br />";
        }
        else {
            $code .= "$attach[attachicon] <span style=\"white-space: nowrap\" id=\"attach_$attach[aid]\" onmouseover=\"showMenu(this.id)\"><a href=\"attachment.php?aid=$attach[aid]\" target=\"_blank\"><strong>$attach[filename]</strong></a> ($attach[attachsize])</span>
			<div class=\"t_attach\" id=\"attach_$attach[aid]_menu\" style=\"position: absolute; display: none\">$attach[attachicon] <a href=\"attachment.php?aid=$attach[aid]\" target=\"_blank\"><strong>$attach[filename]</strong></a> ($attach[attachsize])<br />";
            if ($attach['description'])
                $code .= "$attach[description]<br />";
            if ($attach['readperm'])
                $code .= "{lang readperm}: $attach[readperm]<br />";

        }
        if ($attach['price'])
        {
            $code.="{lang price}: {$extcredits[$creditstrans][title]} $attach[price] {$extcredits[$creditstrans][unit]} &nbsp;<a href=\"misc.php?action=viewattachpayments&amp;aid=$attach[aid]\" target=\"_blank\">[{lang pay_view}]</a>";
            if (!$attach['payed'])
                $code.="&nbsp;<a href=\"misc.php?action=attachpay&amp;aid=$attach[aid]\" target=\"_blank\">[{lang attachment_buy}]</a>";
        }
        $code.="<div class=\"t_smallfont\">$attach[dateline]</div></div>";

    }
    else
        $code.="$attach[attachicon] <strong>{lang attach_pay}: $attach[filename]</strong>";//收费附件

    return $code;
}
function censor($message) {
	global $_DCACHE;
	require_once(DISCUZ_ROOT.'/forumdata/cache/cache_censor.php');

	if($_DCACHE['censor']['banned']) //被禁止关键字
	{
	    $bbcodes_display=($_DCACHE['bbcodes_display'] ? '|'.implode('|', array_keys($_DCACHE['bbcodes_display'])): '');//可用状态bbcode代码
		$bbcodes = 'b|i|u|color|size|font|align|list|indent|url|email|hide|quote|code|free|table|tr|td|img|swf|attach|payto|float'.$bbcodes_display ;
        // 不判断bbcode里面是否有敏感字符
        $filtermsg=@preg_replace(array("/\[($bbcodes)=?.*\]/iU", "/\[\/($bbcodes)\]/i"), '', $message);
		if(preg_match($_DCACHE['censor']['banned'],$filtermsg )) {
			showmessage('word_banned');
		}
	}
	return empty($_DCACHE['censor']['filter']) ? $message :
		@preg_replace($_DCACHE['censor']['filter']['find'], $_DCACHE['censor']['filter']['replace'], $message);
}

//是否要需要审核的关键字
function censormod($message)
{
	global $_DCACHE;
	require_once(DISCUZ_ROOT.'/forumdata/cache/cache_censor.php');
	return $_DCACHE['censor']['mod'] && preg_match($_DCACHE['censor']['mod'], $message);
}

function creditshide($creditsrequire, $message, $pid) {
	global $hideattach;

	if($GLOBALS['credits'] < $creditsrequire && !$GLOBALS['forum']['ismoderator']) {
		$hideattach[$pid] = 1;
		return tpl_hide_credits_hidden($creditsrequire);
	} else {
		$hideattach[$pid] = 0;
		return tpl_hide_credits($creditsrequire, str_replace('\\"', '"', $message));
	}
}

function tpl_hide_credits_hidden($creditsrequire) {
    global $hideattach;
$code='<div class="notice" style="width: 500px">{lang post_hide_credits_hidden}</div>';// '本帖隐藏的内容需要积分高于 $creditsrequire 才可浏览',
    return $code;
}
function tpl_hide_credits($creditsrequire, $message) {
    global $hideattach;
$code='<div class="notice" style="width: 500px">{lang post_hide_credits}</div>
$message<br /><br />
<br />';//'以下内容需要积分高于 $creditsrequire 才可浏览'
return $code;
}


function tpl_codedisp($discuzcodes, $code)
{
//$discuzcodes[codecount] 也是数组下标
	$name='code'.$discuzcodes[codecount];
    $code='<div class="blockcode"><span class="headactions" onclick="copycode($('.$name.'}));">
{lang discuzcode_copyclipboard}</span><h5>{lang discuzcode_code}:</h5><code id="code$discuzcodes[codecount]">$code</code></div>=';

    return $code;

}
function karmaimg($rate, $ratetimes) {
	$karmaimg = '';
	if($rate && $ratetimes) {
		$image = $rate > 0 ? 'agree.gif' : 'disagree.gif';
		for($i = 0; $i < ceil(abs($rate) / $ratetimes); $i++) {
			$karmaimg .= '<img src="'.IMGDIR.'/'.$image.'" border="0" alt="" />';
		}
	}
	return $karmaimg;
}
//$message = preg_replace("/\s*\[code\](.+?)\[\/code\]\s*/ies", "codedisp('\\1')", $message);  [code]Discuz! Board 是由康盛创想（北京）科技有限公司开发的论坛软件[/code]
function codedisp($code) {
    global $discuzcodes;
    $discuzcodes['pcodecount']++;//pcodecount 是数组索引,从0开始保存在codehtml数组里
    //$discuzcodes[codecount] 也是数组下标,从0开始,取$discuzcodes数组
    $code = htmlspecialchars(str_replace('\\"', '"', preg_replace("/^[\n\r]*(.+?)[\n\r]*$/is", "\\1", $code)));//去掉\n\r
    $discuzcodes['codehtml'][$discuzcodes['pcodecount']] = tpl_codedisp($discuzcodes, $code);
    $discuzcodes['codecount']++;
    return "[\tDISCUZ_CODE_$discuzcodes[pcodecount]\t]";
}
function jammer() {
    $randomstr = '';
    for($i = 0; $i < mt_rand(5, 15); $i++) {
        $randomstr .= chr(mt_rand(32, 59)).' '.chr(mt_rand(63, 126));
    }
    $seo = !$GLOBALS['tagstatus'] ? $GLOBALS['discuzcodes']['seoarray'][mt_rand(0, 5)] : '';
    return mt_rand(0, 1) ? '<font style="font-size:0px;color:'.TABLEBG.'">'.$seo.$randomstr.'</font>'."\r\n" :
        "\r\n".'<span style="display:none">'.$randomstr.$seo.'</span>';
}

/*
  $message_preview = discuzcode($message, !empty($smileyoff), !empty($bbcodeoff), !empty($htmlon), $forum['allowsmilies'], $forum['allowbbcode'], $forum['allowimgcode'],
            $forum['allowhtml'], 0, 1);
 $smileyoff  发贴时是否关闭smile 表情标签解析
$bbcodeoff   发贴时是否关闭bbocde标签
$htmlon  ($allowhtml && !empty($htmlon) 发贴时启用 Html 代码 选择“是”则无论论坛设置是否允许，该用户组的作者都可以选择在帖子中直接使用 HTML 代码
$allowsmilies 论坛允许使用发贴时是否关闭smile
$allowbbcode 论坛允许使用发贴时是否关闭bbocde标签  加用户组
$allowimgcode 论坛允许使用允许使用 [img] 代码: ($forum['allowimgcode'] && $showimages ? 1 : 0)
$allowhtml 论坛允许使用 HTML 代码:
$jammer 在帖子内容中增加随机的干扰字串，使得访问者无法复制原始内容 ($forum['jammer'] && $post['authorid'] != $discuz_uid ? 1 : 0)
$parsetype 1 不会解析code,quote,free,swf,bbcode标签
$authorid 发成功的帖子作者ID
$allowmediacode 允许使用media标签
$pid 帖子ID 标记帖子是否需要隐藏
 */
 function discuzcode($message, $smileyoff, $bbcodeoff, $htmlon = 0, $allowsmilies = 1, $allowbbcode = 1, $allowimgcode = 1, $allowhtml = 0,
                    $jammer = 0, $parsetype = '0', $authorid = '0', $allowmediacode = '0', $pid = 0)
{
	global $discuzcodes, $credits, $tid, $discuz_uid, $highlight, $maxsmilies, $db, $tablepre, $hideattach;
    //$discuzcodes 在文件是前面
	if($parsetype != 1 && !$bbcodeoff && $allowbbcode && (strpos($message, '[/code]') || strpos($message, '[/CODE]')) !== FALSE)
	{
		$message = preg_replace("/\s*\[code\](.+?)\[\/code\]\s*/ies", "codedisp('\\1')", $message);//因为code里面代码可能与下面替换冲突(使用了html,bbcode),所以暂时 替换code代码 [\tDISCUZ_CODE_0\t]
	}

	$msglower = strtolower($message);
	if(!$htmlon && !$allowhtml) //论坛不允许使用html标签,dhtmlspecialchars转义html <标签   ,用&&是因为只要用户组或论坛一个允许就能使用html标签
	{
		$message = $jammer ? preg_replace("/\r\n|\n|\r/e", "jammer()", dhtmlspecialchars($message)) : dhtmlspecialchars($message);
        //每行加一串随机字符串<font style="font-size:0px;color:#FFF">* j( Q4 l+ u+ ]! G</font>
	}

	if(!$smileyoff && $allowsmilies && !empty($GLOBALS['_DCACHE']['smilies']) && is_array($GLOBALS['_DCACHE']['smilies']))
	{
		if(!$discuzcodes['smiliesreplaced'])
		{

			foreach($GLOBALS['_DCACHE']['smilies']['replacearray'] AS $key => $smiley)
			{
                $smiletype=$GLOBALS['_DCACHE']['smilies']['typearray'][$key];
/*$_DCACHE['smileytypes'] = array (
  1 =>
  array (
    'name' => '默认表情',
    'directory' => 'default',
  ),
);*/
				$GLOBALS['_DCACHE']['smilies']['replacearray'][$key] = '<img src="images/smilies/'.
                    $GLOBALS['_DCACHE']['smileytypes'][$smiletype]['directory'].'/'.$smiley.'" smilieid="'.$key.'" border="0" alt="" />';
			}
			$discuzcodes['smiliesreplaced'] = 1;
		}

		//$maxsmilies 在一篇帖子中解析的单一表情符号的最大次数，超过此次数限制的表情将不被解析而保留原样，以避免用户在一篇帖子中恶意发表大量表情影响正常阅读
		$message = preg_replace($GLOBALS['_DCACHE']['smilies']['searcharray'], $GLOBALS['_DCACHE']['smilies']['replacearray'], $message, $maxsmilies);
	}

	if(!$bbcodeoff && $allowbbcode)
	{
//[url]http://www.comsenz.com[/url] [url=http://www.Discuz.net]Discuz! 论坛[/url]
        //\1是链接地址=http://www.comsenz.com 或www \2为hhtp或www \3是http \4 非[非"非'的字符多个字符Discuz.net   \5 链接地址
        //([^\["']+?))? 是可能=地址也可以没有
		if(strpos($msglower, '[/url]') !== FALSE) {
			$message = preg_replace("/\[url(=((https?|ftp|gopher|news|telnet|rtsp|mms|callto|bctp|ed2k|thunder|synacast){1}:\/\/|www\.)([^\[\"']+?))?\](.+?)\[\/url\]/ies",
                "parseurl('\\1', '\\5')", $message);
		}
//[email]myname@mydomain.com[/email] [email=support@discuz.net]Discuz! 技术支持[/email]
        //\1 是=邮件地址  \2是support  \3 discuz.net \4 是技术支持
		if(strpos($msglower, '[/email]') !== FALSE) {
			$message = preg_replace("/\[email(=([a-z0-9\-_.+]+)@([a-z0-9\-_]+[.][a-z0-9\-_.]+))?\](.+?)\[\/email\]/ies", "parseemail('\\1', '\\4')", $message);
		}
		//[color=red]红颜色[/color] [size=3]文字大小为 3[/size] [font=仿宋]字体为仿宋[/font] [align=Center]内容居中[/align]
        $message =preg_replace(array(
            "/\[color=([#\w]+?)\]/i",
            "/\[size=(\d+?)\]/i",
            "/\[size=(\d+(\.\d+)?(px|pt|in|cm|mm|pc|em|ex|%)+?)\]/i",//[size=7.2px] +?  ?是非贪模式,尽量匹配到第一个px]
            "/\[font=([^\[\<]+?)\]/i",
            "/\[align=(left|center|right)\]/i",
            "/\[float=(left|right)\]/i"

        ), array(
            "<font color=\"\\1\">",
            "<font size=\"\\1\">",
            "<font style=\"font-size: \\1\">",
            "<font face=\"\\1 \">",
            "<p align=\"\\1\">",
            "<span style=\"float: \\1;\">"
        ), $message);

		$message = str_replace(array(
			'[/color]', '[/size]', '[/font]', '[/align]', '[b]', '[/b]',
			'[i]', '[/i]', '[u]', '[/u]', '[list]', '[list=1]', '[list=a]',
			'[list=A]', '[*]', '[/list]', '[indent]', '[/indent]', '[/float]'
		), array(
			'</font>', '</font>', '</font>', '</p>', '<strong>', '</strong>', '<i>',
			'</i>', '<u>', '</u>', '<ul>', '<ul type="1">', '<ul type="a">',
			'<ul type="A">', '<li>', '</ul>', '<blockquote>', '</blockquote>', '</span>'
		), $message);

		$nest = 0;
        //https://www.discuz.net/thread-2377192-1-1.html
        /*
         * [table=98%,yellow]
[tr=black][td=1,2]例子5[/td][td]例子5[/td][/tr]
[tr][td]例子5[/td][/tr]

[tr=green][td=2,1]你妹的例子5[/td][/tr]
[/table]
        */
        //“？：bai”非获取匹配，匹配冒号后的内du容但不获取匹配结果zhi，不进行存储供以后使dao用
        //(?:=(\d{1,4}%?)  \1是匹配98%,不匹配=98%,yellow
        // (?:,([\(\)%,#\w ]+))?  \2 是匹配yellow  不匹配,yellow
        //    (.+?) \3 匹配table里面内容
		while(strpos($msglower, '[table') !== FALSE && strpos($msglower, '[/table]') !== FALSE){
			$message = preg_replace("/\[table(?:=(\d{1,4}%?)(?:,([\(\)%,#\w ]+))?)?\]\s*(.+?)\s*\[\/table\]/ies", "parsetable('\\1', '\\2', '\\3')", $message);
			if(++$nest > 4) break;//
		}

		if($parsetype != 1)
		{
			if(strpos($msglower, '[/quote]') !== FALSE) {
				$message = preg_replace("/\s*\[quote\][\n\r]*(.+?)[\n\r]*\[\/quote\]\s*/is", tpl_quote(), $message);
			}
			if(strpos($msglower, '[/free]') !== FALSE) {
				$message = preg_replace("/\s*\[free\][\n\r]*(.+?)[\n\r]*\[\/free\]\s*/is", tpl_free(), $message);
			}
		}
//[media=mp3,400,300,1]多媒体 URL[/media]
		if(strpos($msglower, '[/media]') !== FALSE) {
			$message = preg_replace("/\[media=(\w{1,4}),(\d{1,4}),(\d{1,4}),(\d)\]\s*([^\[\<\r\n]+?)\s*\[\/media\]/ies",
                $allowmediacode ?"parsemedia('\\1', \\2, \\3, \\4, '\\5')" : "bbcodeurl('\\5', '<a href=\"%s\" target=\"_blank\">%s</a>')", $message);
		}
//$forum['allowbbcode'] = $forum['allowbbcode'] ? ($_DCACHE['usergroups'][$post['groupid']]['allowcusbbcode'] ? 2 : 1) : 0;
		if($parsetype != 1 && $allowbbcode == 2 && $GLOBALS['_DCACHE']['bbcodes']) {
			$message = preg_replace($GLOBALS['_DCACHE']['bbcodes']['searcharray'], $GLOBALS['_DCACHE']['bbcodes']['replacearray'], $message);
		}
//hide]隐藏内容 Abc[/hide] [hide=20]隐藏内容 Abc[/hide]
		if($parsetype != 1 && strpos($msglower, '[/hide]') !== FALSE) {
			if(strpos($msglower, '[hide]') !== FALSE)//内容隐藏,需要回复才可见或者是管理员
			{
				$query = $db->query("SELECT pid FROM {$tablepre}posts WHERE tid='$tid' AND ".($discuz_uid ? "authorid='$discuz_uid'" : "authorid=0 AND useip='$GLOBALS[onlineip]'")." LIMIT 1");
				if($GLOBALS['forum']['ismoderator'] || $apid = $db->result($query, 0)) //有回复
				{//显示隐藏内容
				    //"<div class=\"notice\" style=\"width: 500px\">{lang post_hide_reply}</div>\\1<br /><br /><br />";// '** 本内容隐藏 **',
					$message = preg_replace("/\[hide\]\s*(.+?)\s*\[\/hide\]/is", tpl_hide_reply(), $message);
					$hideattach[$apid] = 0;
				} else
                {
				    //"<div class=\"notice\" style=\"width: 500px\">{lang post_hide_reply_hidden}</div>" 本帖隐藏的内容需要回复才可以浏览
					$message = preg_replace("/\[hide\](.+?)\[\/hide\]/is", tpl_hide_reply_hidden(), $message);
					$hideattach[$pid] = 0;
				}
			}
			//'本帖隐藏的内容需要积分高于 $creditsrequire 才可浏览',
			if(strpos($msglower, '[hide=') !== FALSE)
			{
				$message = preg_replace("/\[hide=(\d+)\]\s*(.+?)\s*\[\/hide\]/ies", "creditshide(\\1,'\\2', $pid)", $message);
			}
		}
	}

	if(!$bbcodeoff)
	{
		if($parsetype != 1 && strpos($msglower, '[swf]') !== FALSE) {
			$message = preg_replace("/\[swf\]\s*([^\[\<\r\n]+?)\s*\[\/swf\]/ies",
                "bbcodeurl('\\1', ' <img src=\"images/attachicons/flash.gif\" align=\"absmiddle\" alt=\"\" /> <a href=\"%s\" target=\"_blank\">Flash: %s</a> ')", $message);
		}

		if(strpos($msglower, '[/img]') !== FALSE)
		{
			$message = preg_replace(array(
				"/\[img\]\s*([^\[\<\r\n]+?)\s*\[\/img\]/ies",//[img]http://www.discuz.net/images/default/logo.gif[/img]
				"/\[img=(\d{1,4})[x|\,](\d{1,4})\]\s*([^\[\<\r\n]+?)\s*\[\/img\]/ies" //[img=88,31]http://www.discuz.net/images/logo.gif[/img]
			), $allowimgcode ? array(
				"bbcodeurl('\\1', '<img src=\"%s\" border=\"0\" onclick=\"zoom(this, this.src)\" onload=\"attachimg(this, \'load\')\" alt=\"\" />')",
				"bbcodeurl('\\3', '<img width=\"\\1\" height=\"\\2\" src=\"%s\" border=\"0\" alt=\"\" />')"
			) : array(
				"bbcodeurl('\\1', '<a href=\"%s\" target=\"_blank\">%s</a>')",
				"bbcodeurl('\\3', '<a href=\"%s\" target=\"_blank\">%s</a>')"
			), $message);
		}
	}

	for($i = 0; $i <= $discuzcodes['pcodecount']; $i++)
	{
		$message = str_replace("[\tDISCUZ_CODE_$i\t]", $discuzcodes['codehtml'][$i], $message);//恢复[code]里面的代码
	}

	if($highlight)//123%2b789
	{//&highlight=123+789    <highlight>高亮文字 </highlight>
		$highlightarray = explode('+', $highlight);
        //查找高亮的文字,在> 里面< ,不能在html标签里面找
		$message = preg_replace(array("/(^|>)([^<]+)(?=<|$)/sUe", "/<highlight>(.*)<\/highlight>/siU"),
            array("highlight('\\2', \$highlightarray, '\\1')", "<strong><font color=\"#FF0000\">\\1</font></strong>"), $message);
	}

	unset($msglower);
    //$htmlon 用户组可以使用html或$allowhtml论坛可以使用Html
    //nl2br 换行转<br>
	return $htmlon || $allowhtml ? $message : nl2br(str_replace(array("\t", '   ', '  '), array('&nbsp; &nbsp; &nbsp; &nbsp; ', '&nbsp; &nbsp;', '&nbsp;&nbsp;'), $message));
}
//$prepend 前缀 >
function highlight($text, $words, $prepend)
{
    $text = str_replace('\"', '"', $text);
    foreach($words AS $key => $replaceword) {
        $text = str_replace($replaceword, '<highlight>'.$replaceword.'</highlight>', $text);
    }
    return "$prepend$text";
}
function tpl_quote() {
    $code="<div class=\"quote\"><h5>{lang discuzcode_quote}:</h5><blockquote>\\1</blockquote></div>";
    return $code;
}

function tpl_free() {
    $code="<div class=\"quote\"><h5>{lang discuzcode_free}:</h5><blockquote>\\1</blockquote></div>";
    return $code;
}

function tpl_hide_reply() {
    global $hideattach;
    $code="<div class=\"notice\" style=\"width: 500px\">{lang post_hide_reply}</div>
\\1<br /><br /><br />";// '** 本内容隐藏 **',
    return $code;}

function tpl_hide_reply_hidden() {
    $code="<div class=\"notice\" style=\"width: 500px\">{lang post_hide_reply_hidden}</div>";
    return $code;
}

//[url]http://www.comsenz.com[/url] [url=http://www.Discuz.net]Discuz! 论坛[/url]
function parseurl($url, $text) {
	if(!$url && preg_match("/((https?|ftp|gopher|news|telnet|rtsp|mms|callto|bctp|ed2k|thunder|synacast){1}:\/\/|www\.)[^\[\"']+/i", trim($text), $matches))
	{//[url]http://www.comsenz.com[/url]
		$url = $matches[0];
		$length = 65;
		if(strlen($url) > $length) {
			$text = substr($url, 0, intval($length * 0.5)).' ... '.substr($url, - intval($length * 0.3));
		}
		return '<a href="'.(substr(strtolower($url), 0, 4) == 'www.' ? 'http://'.$url : $url).'" target="_blank">'.$text.'</a>';
	} else {
	    //[url=http://www.Discuz.net]Discuz! 论坛[/url]
		$url = substr($url, 1);
		if(substr(strtolower($url), 0, 4) == 'www.') {
			$url = 'http://'.$url;
		}
		return '<a href="'.$url.'" target="_blank">'.$text.'</a>';
	}
}
//[email]myname@mydomain.com[/email] [email=support@discuz.net]Discuz! 技术支持[/email]
function parseemail($email, $text)
{
	if(!$email && preg_match("/\s*([a-z0-9\-_.+]+)@([a-z0-9\-_]+[.][a-z0-9\-_.]+)\s*/i", $text, $matches)) {
		$email = trim($matches[0]);
		return '<a href="mailto:'.$email.'">'.$email.'</a>';
	} else {
		return '<a href="mailto:'.substr($email, 1).'">'.$text.'</a>';
	}
}
//[table=98%,yellow]
function parsetable($width, $bgcolor, $message)
{//[tr=green][td=2,1,20%]你妹的例子5[/td][/tr]
    $match1=preg_match("/^\[tr(?:=([\(\)%,#\w]+))?\]\s*\[td(?:=(\d{1,2}),(\d{1,2})(?:,(\d{1,4}%?))?)?\]/", $message);
    $match2=preg_match("/^<tr[^>]*?>\s*<td[^>]*?>/", $message);//<tr>sdfsdfsd<td>xxx
	if(!$match1 && !$match2)//table里面格式不正确
	{//去掉tr,td标签,不要表格了
		return str_replace('\\"', '"', preg_replace("/\[tr(?:=([\(\)%,#\w]+))?\]|\[td(?:=(\d{1,2}),(\d{1,2})(?:,(\d{1,4}%?))?)?\]|\[\/td\]|\[\/tr\]/", '', $message));
	}
	$width = substr($width, -1) == '%' ? (substr($width, 0, -1) <= 98 ? intval($width).'%' : '98%') : ($width <= 560 ? intval($width).'px' : '98%');
	return '<table cellspacing="0" class="t_table" '.
		($width == '' ? NULL : 'style="width:'.$width.'"').
		($bgcolor ? ' bgcolor="'.$bgcolor.'">' : '>').
		str_replace('\\"', '"', preg_replace(array(
				"/\[tr(?:=([\(\)%,#\w]+))?\]\s*\[td(?:=(\d{1,2}),(\d{1,2})(?:,(\d{1,4}%?))?)?\]/ie",//下一行[tr=green][td=2,1,20%]
				"/\[\/td\]\s*\[td(?:=(\d{1,2}),(\d{1,2})(?:,(\d{1,4}%?))?)?\]/ie",//下一列 [/td][td=2,1,20%]
				"/\[\/td\]\s*\[\/tr\]/i"//当前行结束
			), array(
				"parsetrtd('\\1', '\\2', '\\3', '\\4')",//\1 green  \2 2  \3 1 \4 20%
				"parsetrtd('td', '\\1', '\\2', '\\3')",
				'</td></tr>'
			), $message)
		).'</table>';
}

function parsetrtd($bgcolor, $colspan, $rowspan, $width) {
	return ($bgcolor == 'td' ? '</td>' : '<tr'.($bgcolor ? ' bgcolor="'.$bgcolor.'"' : '').'>').'<td'.($colspan > 1 ? ' colspan="'.$colspan.'"' : '').
    ($rowspan > 1 ? ' rowspan="'.$rowspan.'"' : '').($width ? ' width="'.$width.'"' : '').'>';
}
//[media=mp3,400,300,1]多媒体 URL[/media]
function parsemedia($type, $width, $height, $autostart, $url) {
	if(in_array($type, array('ra', 'rm', 'wma', 'wmv', 'mp3', 'mov'))) {
		$url = str_replace(array('<', '>'), '', str_replace('\\"', '\"', $url));
		$mediaid = 'media_'.random(3);
		switch($type) {
			case 'ra'	: return '<object classid="clsid:CFCDAA03-8BE4-11CF-B84B-0020AFBBCCFA" width="'.$width.'" height="32"><param name="autostart" value="'.$autostart.'" /><param name="src" value="'.$url.'" /><param name="controls" value="controlpanel" /><param name="console" value="'.$mediaid.'_" /><embed src="'.$url.'" type="audio/x-pn-realaudio-plugin" controls="ControlPanel" '.($autostart ? 'autostart="true"' : '').' console="'.$mediaid.'_" width="'.$width.'" height="32"></embed></object>';break;
			case 'rm'	: return '<object classid="clsid:CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA" width="'.$width.'" height="'.$height.'"><param name="autostart" value="'.$autostart.'" /><param name="src" value="'.$url.'" /><param name="controls" value="imagewindow" /><param name="console" value="'.$mediaid.'_" /><embed src="'.$url.'" type="audio/x-pn-realaudio-plugin" controls="IMAGEWINDOW" console="'.$mediaid.'_" width="'.$width.'" height="'.$height.'"></embed></object><br /><object classid="clsid:CFCDAA03-8BE4-11CF-B84B-0020AFBBCCFA" width="'.$width.'" height="32"><param name="src" value="'.$url.'" /><param name="controls" value="controlpanel" /><param name="console" value="'.$mediaid.'_" /><embed src="'.$url.'" type="audio/x-pn-realaudio-plugin" controls="ControlPanel" '.($autostart ? 'autostart="true"' : '').' console="'.$mediaid.'_" width="'.$width.'" height="32"></embed></object>';break;
			case 'wma'	: return '<object classid="clsid:6BF52A52-394A-11d3-B153-00C04F79FAA6" width="'.$width.'" height="64"><param name="autostart" value="'.$autostart.'" /><param name="url" value="'.$url.'" /><embed src="'.$url.'" autostart="'.$autostart.'" type="audio/x-ms-wma" width="'.$width.'" height="64"></embed></object>';break;
			case 'wmv'	: return '<object classid="clsid:6BF52A52-394A-11d3-B153-00C04F79FAA6" width="'.$width.'" height="'.$height.'"><param name="autostart" value="'.$autostart.'" /><param name="url" value="'.$url.'" /><embed src="'.$url.'" autostart="'.$autostart.'" type="video/x-ms-wmv" width="'.$width.'" height="'.$height.'"></embed></object>';break;
			case 'mp3'	: return '<object classid="clsid:6BF52A52-394A-11d3-B153-00C04F79FAA6" width="'.$width.'" height="64"><param name="autostart" value="'.$autostart.'" /><param name="url" value="'.$url.'" /><embed src="'.$url.'" autostart="'.$autostart.'" type="application/x-mplayer2" width="'.$width.'" height="64"></embed></object>';break;
			case 'mov'	: return '<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" width="'.$width.'" height="'.$height.'"><param name="autostart" value="'.($autostart ? 'true' : 'false').'" /><param name="src" value="'.$url.'" /><embed controller="true" width="'.$width.'" height="'.$height.'" src="'.$url.'" autostart="'.($autostart ? 'true' : 'false').'"></embed></object>';break;
		}
	}
	return;
}

function videocode($message, $tid, $pid) {
	global $vsiteid, $vsiteurl, $boardurl;
	$vsiteurl = urlencode($vsiteurl);
	$playurl = "http://union.bokecc.com/flash/discuz2/player.swf?siteid=$vsiteid&vid=\\2&tid=$tid&pid=$pid&autoStart=\\1&referer=".urlencode($boardurl."redirect.php?goto=findpost&pid=$pid&ptid=$tid");
	$flashplayer = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="object_flash_player" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" height="373" width="438">';
	$flashplayer .= '<param name="movie" value="'.$playurl.'">';
	$flashplayer .= '<param name="quality" value="high">';
	$flashplayer .= '<param name="allowScriptAccess" value="always">';
	$flashplayer .= '<param name="allowFullScreen" value="true">';
	$flashplayer .= '<embed src="'.$playurl.'" allowScriptAccess="always" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer"type="application/x-shockwave-flash" allowfullscreen="true" height="373" width="438">';
	$flashplayer .= '</object>';
	return preg_replace("/\[video=(\d)\](\w+)\[\/video\]/", "$flashplayer", $message);
}

function bbcodeurl($url, $tags) {
	if(!preg_match("/<.+?>/s", $url)) {
		if(!in_array(strtolower(substr($url, 0, 6)), array('http:/', 'https:', 'ftp://', 'rtsp:/', 'mms://'))) {
			$url = 'http://'.$url;
		}
		return str_replace(array('submit', 'logging.php'), array('', ''), sprintf($tags, $url, addslashes($url)));
	} else {
		return '&nbsp;'.$url;
	}
}




?>